import os, sys, subprocess, time

def Execute(command, *args, **kwargs):
  # execute the management utility, with the same python path as the current process
  env = dict(os.environ)
  paths = list(sys.path)
  cdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
  paths.append(cdir)
  env['PYTHONPATH'] = os.pathsep.join(paths)
  stdout, stderr = None, subprocess.STDOUT
  if 'stdout' in kwargs: 
    stdout = kwargs['stdout']
    del kwargs['stdout']
  if 'stderr' in kwargs: 
    stderr = kwargs['stderr'] 
    del kwargs['stderr']  
  cargs = [sys.executable, os.path.join(cdir, 'manage.py'), command,]
  cargs.extend([str(a) for a in args])
  cargs.extend(['--'+str(k)+'='+str(v) for k,v in kwargs.items()])
  print cargs
  proc = subprocess.Popen(cargs,
                          stdout=stdout,
                          stderr=stderr,
                          close_fds=True, 
                          env=env, bufsize=4096)
  return proc
    
def Log(proc, stdoutMethod, stderrMethod):
  #Start logging
  import select
  writers = {}
  writers[proc.stdout] = [stdoutMethod, '',]
  writers[proc.stderr] = [stderrMethod, '',]
  t = time.time()
  while True:
    data = select.select([proc.stdout, proc.stderr],[],[], 0)[0]
    for d in data:
      writers[d][1] += d.read(1)
    if all([writers[w][1] == '' for w in writers]) and proc.poll() != None: break
    if (time.time() - t > 1): # Save the log once every second max
      for w in writers:
        writers[w][0](writers[w][1])
        writers[w][1] = ''
      t = time.time()
  for w in writers:
    writers[w][0](writers[w][1])
